package cn.cds.withyou.admin.actions;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import cn.cds.withyou.admin.Application;
import cn.cds.withyou.lib.Constants;
import cn.cds.withyou.lib.model.ActivityDto;
import cn.cds.withyou.lib.model.ArenaDto;
import cn.cds.withyou.lib.model.CourseDto;
import cn.cds.withyou.lib.model.FeedbackDto;
import cn.cds.withyou.lib.model.GameDto;
import cn.cds.withyou.lib.model.MemberRequestDto;
import cn.cds.withyou.lib.model.VIPRequestDto;
import cn.ljs.android.actions.DataBundle;
import cn.ljs.android.buses.ActionBus;
import cn.ljs.android.helper.TaskExecutor;

/**
 * <p> Description: </p>
 * <p/>
 * <p> Copyright: Copyright (c) 2016 </p>
 *
 * @author: Json.Lee
 * @Version: 1.0
 * @CreateTime: 7/5/2016 11:07
 */
public class ActionsCreator {

    private static ActionsCreator INSTANCE;

    protected ActionBus mBus;

    protected ActionsCreator(ActionBus bus) {
        this.mBus = bus;
    }

    public static ActionsCreator get() {
        if (null == INSTANCE) {
            INSTANCE = new ActionsCreator(Application.getInstance().getActionsBus());
        }
        return INSTANCE;
    }

    private final static SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static {
        DATE_TIME_FORMAT.setTimeZone(TimeZone.getDefault());
    }

    public void requestMemberRequest() {
        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {
                RequestActions actions = new RequestActions();
                actions.setData(new DataBundle());

                Cursor result = getProvider().query(Constants.MemberRequest.URI, Constants.MemberRequest._ITEMS, null, null, TextUtils.concat(Constants.MemberRequest._CREATE_TIME, " desc").toString());
                if (null != result) {
                    actions.setAction(RequestActions.LOAD_MEMBER_REQUEST_SUCC);
                    List<MemberRequestDto> requests = new ArrayList<>();
                    if (result.getCount() > 0 && result.moveToFirst()) {
                        do {
                            requests.add(new MemberRequestDto(result));
                        } while (result.moveToNext());
                    }
                    result.close();
                    actions.getData().put(RequestActions.KEY_DATA_INFO.hashCode(), requests);
                } else {
                    actions.setAction(RequestActions.LOAD_MEMBER_REQUEST_FAIL);
                }
                mBus.dispatch(actions);
            }
        });
    }

    public void requestVIPRequest() {
        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {
                RequestActions actions = new RequestActions();
                actions.setData(new DataBundle());

                Cursor result = getProvider().query(Constants.VIPRequest.URI, Constants.VIPRequest._ITEMS, null, null, TextUtils.concat(Constants.VIPRequest._CREATE_TIME, " desc").toString());
                if (null != result) {
                    List<VIPRequestDto> list = new ArrayList<>();
                    actions.setAction(RequestActions.LOAD_VIP_REQUEST_SUCC);
                    if (result.getCount() > 0 && result.moveToFirst()) {
                        do {
                            list.add(new VIPRequestDto(result));
                        } while (result.moveToNext());
                    }
                    result.close();
                    actions.getData().put(RequestActions.KEY_DATA_INFO.hashCode(), list);
                } else {
                    actions.setAction(RequestActions.LOAD_VIP_REQUEST_FAIL);
                }
                mBus.dispatch(actions);
            }
        });
    }

    public void requestVIPRequestHandle(final VIPRequestDto dto, final boolean accept) {
        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {
                RequestActions actions = new RequestActions();
                ContentValues values = new ContentValues();
                values.put(Constants.VIPRequest._PASSED_ITEM, accept ? VIPRequestDto.ACCEPT : VIPRequestDto.REJECT);

                if (getProvider().update(Constants.VIPRequest.URI, values, TextUtils.concat(Constants._ID, " = ? ").toString(), new String[]{dto.getId()}) > 0) {
                    actions.setAction(RequestActions.HANDLE_VIP_REQ_SUCC);
                } else {
                    actions.setAction(RequestActions.HANDLE_VIP_REQ_FAIL);
                }
                mBus.dispatch(actions);
            }
        });
    }

    public void requestMemberRequestHandle(final MemberRequestDto dto, final boolean accept) {
        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {
                RequestActions actions = new RequestActions();
                ContentValues values = new ContentValues();
                values.put(Constants.MemberRequest._PASSED_ITEM, accept ? MemberRequestDto.ACCEPT : MemberRequestDto.REJECT);

                if (getProvider().update(Constants.MemberRequest.URI, values, TextUtils.concat(Constants._ID, " = ? ").toString(), new String[]{dto.getId()}) > 0) {
                    actions.setAction(RequestActions.HANDLE_MEMBER_REQ_SUCC);
                } else {
                    actions.setAction(RequestActions.HANDLE_MEMBER_REQ_FAIL);
                }
                mBus.dispatch(actions);
            }
        });
    }

    public void requestAllFeedback () {
        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {
                FeedbackActions actions = new FeedbackActions();
                actions.setData(new DataBundle());

                Cursor result = getProvider().query(Constants.FeedBack.URI, Constants.FeedBack._ITEMS, null, null, TextUtils.concat(Constants.FeedBack._TIME_ITEM, " desc").toString());
                if (null != result) {
                    actions.setAction(FeedbackActions.LOAD_FEEDBACK_SUCC);
                    List<FeedbackDto> list = new ArrayList<>();
                    if (result.getCount() > 0 && result.moveToFirst()) {
                        do {
                            list.add(new FeedbackDto(result));
                        } while (result.moveToNext());
                    }
                    result.close();
                    actions.getData().put(FeedbackActions.KEY_DATA_INFO.hashCode(), list);
                } else {
                    actions.setAction(FeedbackActions.LOAD_FEEDBACK_FAIL);
                }
                mBus.dispatch(actions);
            }
        });
    }

    public void requestCourseAdded (@NonNull final CourseDto course) {
        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {
                CourseActions actions = new CourseActions();

                ContentValues values = new ContentValues();
                values.put(Constants.Course._TITLE_ITEM, course.getTitle());
                values.put(Constants.Course._CONTENT_ITEM, course.getContent());
                values.put(Constants.Course._PIC_ITEM, course.getPic());
                values.put(Constants.Course._COURSE_URL, course.getUrl());

                if (ContentUris.parseId(getProvider().insert(Constants.Course.URI, values)) > 0) {
                    actions.setAction(CourseActions.ADD_COURSE_SUCC);
                } else {
                    actions.setAction(CourseActions.ADD_COURSE_FAIL);
                }
                mBus.dispatch(actions);
            }
        });
    }

    public void requestArenaAdded (@NonNull final ArenaDto arena) {
        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {
                ArenaActions actions = new ArenaActions();

                ContentValues values = new ContentValues();
                values.put(Constants.Arena._NAME_ITEM, arena.getName());
                values.put(Constants.Arena._PHONE_ITEM, arena.getPhone());
                values.put(Constants.Arena._ADDRESS_ITEM, arena.getAddress());
                values.put(Constants.Arena._PIC_ITEM, arena.getPic());
                values.put(Constants.Arena._COMMENT_ITEM, arena.getComment());
                values.put(Constants.Arena._SPACE_COUNT, arena.getSpaceCount());

                if (ContentUris.parseId(getProvider().insert(Constants.Arena.URI, values)) > 0) {
                    actions.setAction(ArenaActions.ARENA_ADDED_SUCC);
                } else {
                    actions.setAction(ArenaActions.ARENA_ADDED_FAIL);
                }
                mBus.dispatch(actions);
            }
        });
    }

    public void requestActivityAdded (@NonNull final ActivityDto act) {
        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {
                ActivityActions actions = new ActivityActions();

                ContentValues values = new ContentValues();
                values.put(Constants.Activity._ACTIVITY_NAME, act.getActivityName());
                values.put(Constants.Activity._ACTIVITY_START_TIME, DATE_TIME_FORMAT.format(new Date(act.getActivityStartT())));
                values.put(Constants.Activity._ACTIVITY_END_TIME, DATE_TIME_FORMAT.format(new Date(act.getActivityEndT())));
                values.put(Constants.Activity._ACTIVITY_ADDRESS, act.getActivityAddress());
                values.put(Constants.Activity._ACTIVITY_PIC, act.getActivityPic());
                values.put(Constants.Activity._ACTIVITY_CONTENT, act.getActivityContent());

                if (ContentUris.parseId(getProvider().insert(Constants.Activity.URI, values)) > 0) {
                    actions.setAction(ActivityActions.ADD_ACTIVITY_SUCC);
                } else {
                    actions.setAction(ActivityActions.ADD_ACTIVITY_FAIL);
                }
                mBus.dispatch(actions);
            }
        });
    }

    public void requestGameAdded (@NonNull final GameDto game) {
        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {
                GameActions actions = new GameActions();

                ContentValues values = new ContentValues();
                values.put(Constants.Game._GAME_NAME, game.getGameName());
                values.put(Constants.Game._SIGNUP_START_TIME, DATE_TIME_FORMAT.format(new Date(game.getSignupStartT())));
                values.put(Constants.Game._SIGNUP_END_TIME, DATE_TIME_FORMAT.format(new Date(game.getSignupEndT())));
                values.put(Constants.Game._GAME_START_TIME, DATE_TIME_FORMAT.format(new Date(game.getGameStartT())));
                values.put(Constants.Game._GAME_END_TIME, DATE_TIME_FORMAT.format(new Date(game.getGameEndT())));
                values.put(Constants.Game._GAME_PIC, game.getGamePic());
                values.put(Constants.Game._GAME_CONTENT, game.getGameContent());

                if (ContentUris.parseId(getProvider().insert(Constants.Game.URI, values)) > 0) {
                    actions.setAction(GameActions.GAME_ADDED_SUCC);
                } else {
                    actions.setAction(GameActions.GAME_ADDED_FAIL);
                }
                mBus.dispatch(actions);
            }
        });
    }

    private ContentResolver getProvider() {
        return Application.getInstance().getContentResolver();
    }
}
